import random
from typing import List, Dict, Callable
from .game_state import WorldEvent, FactorDevelopment

class EventSystem:
    """事件系统管理器"""
    
    def __init__(self):
        self.random_events = self._init_random_events()
        self.event_handlers = {}
        self._register_handlers()
    
    def _init_random_events(self) -> List[WorldEvent]:
        """初始化随机事件"""
        return [
            WorldEvent(
                name="神秘商人",
                trigger_time=random.randint(50, 200),
                location=(random.uniform(0, 100), random.uniform(0, 100)),
                duration=20,
                rewards={"gold": 100, "items": ["治疗药水"]},
                requirements={},
                description="神秘的旅行商人出现在附近"
            ),
            WorldEvent(
                name="古代遗迹",
                trigger_time=random.randint(150, 400), 
                location=(random.uniform(0, 100), random.uniform(0, 100)),
                duration=30,
                rewards={"experience": 200, "attributes": {"perception": 10}},
                requirements={"min_level": 5},
                description="发现一座古老的遗迹，里面可能藏有宝藏"
            ),
            # 更多随机事件...
        ]
    
    def _register_handlers(self):
        """注册事件处理器"""
        self.event_handlers = {
            "sky_titan": self._handle_sky_titan,
            "earth_titan": self._handle_earth_titan,
            "mystery_merchant": self._handle_mystery_merchant,
            "ancient_ruins": self._handle_ancient_ruins
        }
    
    def generate_random_event(self, current_time: int) -> WorldEvent:
        """生成随机事件"""
        available_events = [e for e in self.random_events if not e.completed]
        if available_events and random.random() < 0.1:  # 10%概率
            event = random.choice(available_events)
            event.trigger_time = current_time + random.randint(1, 50)
            return event
        return None
    
    def handle_event(self, event: WorldEvent, participants: List[FactorDevelopment]) -> Dict:
        """处理事件"""
        handler = self.event_handlers.get(event.name)
        if handler:
            return handler(event, participants)
        return self._handle_default_event(event, participants)
    
    def _handle_sky_titan(self, event: WorldEvent, participants: List[FactorDevelopment]) -> Dict:
        """处理天空泰坦事件"""
        results = {
            "participants": [f.name for f in participants],
            "damage_dealt": 0,
            "rewards_earned": {}
        }
        
        total_attack = sum(f.attributes['attack'] for f in participants)
        titan_defeated = total_attack > 8000  # 泰坦难度
        
        if titan_defeated:
            results["rewards_earned"] = event.rewards
            results["message"] = "成功击败天空泰坦!"
        else:
            results["message"] = "未能击败天空泰坦，需要更强大的力量"
            
        return results
    
    def _handle_mystery_merchant(self, event: WorldEvent, participants: List[FactorDevelopment]) -> Dict:
        """处理神秘商人事件"""
        results = {
            "participants": [f.name for f in participants],
            "transactions": []
        }
        
        for factor in participants:
            if random.random() < 0.7:  # 70%概率成功交易
                transaction = {
                    "factor": factor.name,
                    "item": random.choice(["治疗药水", "力量药剂", "速度之靴"]),
                    "cost": random.randint(10, 50)
                }
                results["transactions"].append(transaction)
                results["message"] = "与神秘商人交易成功"
        
        return results
    
    def _handle_default_event(self, event: WorldEvent, participants: List[FactorDevelopment]) -> Dict:
        """默认事件处理器"""
        return {
            "participants": [f.name for f in participants],
            "message": f"参与了 {event.name} 事件",
            "rewards": event.rewards
        }